// api.ts  
const API_URL = process.env.REACT_APP_API_URL;

interface ApiOptions {
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    headers?: Record<string, string>;
    body?: any;
}

export const fetchApi = async (endpoint: string, options: ApiOptions = {}) => {
    const token = localStorage.getItem('token');
    const defaultHeaders = {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
    };

    const response = await fetch(`${API_URL}${endpoint}`, {
        ...options,
        headers: {
            ...defaultHeaders,
            ...options.headers,
        },
    });

    if (!response.ok) {
        throw new Error('网络响应不是 OK');
    }

    // 假设所有响应都是 JSON 格式  
    return await response.json();
};